package leetcode.code1815;

import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;

public class Solution implements IDebug {

	int size;

	public int maxHappyGroups(int batchSize, int[] groups) {
		size = batchSize;
		int[] h = new int[size];
		for (int g : groups) {
			h[g % size]++;
		}
		long rest = 0;
		for (int i = 1; i < size; i++) {
			rest |= (1l * h[i]) << ((i - 1) * 5);
		}
		Map<Long, Integer> dp = new HashMap<>();
		return f(rest, dp) + h[0];
	}

	private int f(long rest, Map<Long, Integer> dp) {
		if (rest == 0) {
			return 0;
		}
		if (dp.containsKey(rest)) {
			return dp.get(rest);
		}
		int sum = 0;
		for (int i = 1; i < size; i++) {
			sum += ((rest >> ((i - 1) * 5)) & 0b11111) * i;
		}
		int ans = 0;
		for (int i = 1; i < size; i++) {
			long num = (rest >> ((i - 1) * 5)) & 0b11111;
			if (num != 0) {
				int cur = f((rest ^ (num << ((i - 1) * 5))) | (((num - 1) << ((i - 1) * 5))), dp);
				if ((sum - i) % size == 0) {
					cur++;
				}
				ans = Math.max(ans, cur);
			}
		}
		dp.put(rest, ans);
		return ans;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
